<template>
    <div class="book-container">
        <!-- 顶部操作栏：标题和新增按钮 -->
        <div class="top-bar">
            <h2>图书管理</h2>
            <el-button type="primary" @click="showAddModal">
                <el-icon><Plus /></el-icon> 新增图书
            </el-button>
        </div>

        <!-- 搜索表单 -->
        <el-card class="search-card" shadow="hover">
            <el-form :model="searchForm" inline class="search-form">
                <el-form-item label="书名">
                    <el-input
                        v-model="searchForm.title"
                        placeholder="请输入书名"
                        clearable
                        style="width: 200px;"
                    />
                </el-form-item>
                <el-form-item label="作者">
                    <el-input
                        v-model="searchForm.author"
                        placeholder="请输入作者"
                        clearable
                        style="width: 200px;"
                    />
                </el-form-item>
                <el-form-item label="ISBN">
                    <el-input
                        v-model="searchForm.isbn"
                        placeholder="请输入ISBN"
                        clearable
                        style="width: 200px;"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchBooks">
                        <el-icon><Search /></el-icon> 搜索
                    </el-button>
                    <el-button @click="resetSearch" style="margin-left: 10px;">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 图书列表表格 -->
        <el-card class="table-card" shadow="hover" style="margin-top: 15px;">
            <el-table
                :data="bookList"
                border
                stripe
                :loading="tableLoading"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="ID" width="80" align="center" />
                <el-table-column prop="isbn" label="ISBN" min-width="120" />
                <el-table-column prop="title" label="书名" min-width="180" />
                <el-table-column prop="author" label="作者" min-width="120" />
                <el-table-column prop="publisher" label="出版社" min-width="150" />
                <el-table-column prop="publicationYear" label="出版年份" width="110" align="center" />
                <el-table-column prop="category" label="分类" min-width="100" />
                <el-table-column prop="quantity" label="总库存" width="90" align="center" />
                <el-table-column prop="availableQuantity" label="可借数量" width="100" align="center">
                    <template #default="scope">
                        <span :class="scope.row.availableQuantity > 0 ? 'text-success' : 'text-danger'">
                            {{ scope.row.availableQuantity }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template #default="scope">
                        <el-button
                            type="primary"
                            size="small"
                            @click="showEditModal(scope.row)"
                            icon="Edit"
                        >
                            编辑
                        </el-button>
                        <el-button
                            type="danger"
                            size="small"
                            @click="deleteBook(scope.row.id)"
                            icon="Delete"
                            style="margin-left: 5px;"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination" v-if="total > 0">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                />
            </div>
        </el-card>

        <!-- 新增/编辑图书弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '新增图书' : '编辑图书'"
            width="600px"
            :close-on-click-modal="false"
        >
            <el-form
                ref="bookForm"
                :model="bookForm"
                :rules="bookRules"
                label-width="120px"
                class="book-form"
            >
                <el-form-item label="ISBN" prop="isbn">
                    <el-input
                        v-model="bookForm.isbn"
                        placeholder="请输入ISBN编号"
                        :disabled="dialogType === 'edit'"  <!-- 编辑时不可修改ISBN -->
                    />
                </el-form-item>
                <el-form-item label="书名" prop="title">
                    <el-input v-model="bookForm.title" placeholder="请输入书名" />
                </el-form-item>
                <el-form-item label="作者" prop="author">
                    <el-input v-model="bookForm.author" placeholder="请输入作者" />
                </el-form-item>
                <el-form-item label="出版社" prop="publisher">
                    <el-input v-model="bookForm.publisher" placeholder="请输入出版社" />
                </el-form-item>
                <el-form-item label="出版年份" prop="publicationYear">
                    <el-input
                        v-model="bookForm.publicationYear"
                        type="number"
                        placeholder="请输入出版年份"
                        min="1000"
                        max="2100"
                    />
                </el-form-item>
                <el-form-item label="图书分类" prop="category">
                    <el-select v-model="bookForm.category" placeholder="请选择分类">
                        <el-option label="文学" value="文学" />
                        <el-option label="科技" value="科技" />
                        <el-option label="历史" value="历史" />
                        <el-option label="哲学" value="哲学" />
                        <el-option label="艺术" value="艺术" />
                        <el-option label="其他" value="其他" />
                    </el-select>
                </el-form-item>
                <el-row :gutter="15">
                    <el-col :span="12">
                        <el-form-item label="总库存" prop="quantity">
                            <el-input
                                v-model="bookForm.quantity"
                                type="number"
                                min="0"
                                placeholder="请输入总库存"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="可借数量" prop="availableQuantity">
                            <el-input
                                v-model="bookForm.availableQuantity"
                                type="number"
                                min="0"
                                placeholder="请输入可借数量"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveBook">确定</el-button>
            </template>
        </el-dialog>

        <!-- 批量删除确认弹窗 -->
        <el-dialog
            v-model="batchDeleteDialog"
            title="批量删除"
            width="400px"
            :close-on-click-modal="false"
        >
            <p>确定要删除选中的 {{ selectedBooks.length }} 本图书吗？</p>
            <template #footer>
                <el-button @click="batchDeleteDialog = false">取消</el-button>
                <el-button type="danger" @click="confirmBatchDelete">确定删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
module.exports = {
    data() {
        return {
            // 图书列表数据
            bookList: [],
            total: 0, // 总记录数
            pageNum: 1, // 当前页码
            pageSize: 10, // 每页条数
            tableLoading: false, // 表格加载状态

            // 搜索表单数据
            searchForm: {
                title: '',
                author: '',
                isbn: ''
            },

            // 弹窗相关
            dialogVisible: false, // 新增/编辑弹窗显示状态
            dialogType: 'add', // 弹窗类型：add/edit
            batchDeleteDialog: false, // 批量删除弹窗

            // 表单数据
            bookForm: {
                id: null,
                isbn: '',
                title: '',
                author: '',
                publisher: '',
                publicationYear: null,
                category: '',
                quantity: 0,
                availableQuantity: 0
            },

            // 选中的图书
            selectedBooks: [],

            // 表单验证规则
            bookRules: {
                isbn: [
                    { required: true, message: '请输入ISBN编号', trigger: 'blur' },
                    { min: 10, max: 13, message: 'ISBN长度为10-13位', trigger: 'blur' }
                ],
                title: [
                    { required: true, message: '请输入书名', trigger: 'blur' },
                    { min: 1, max: 100, message: '书名长度为1-100位', trigger: 'blur' }
                ],
                author: [
                    { required: true, message: '请输入作者', trigger: 'blur' },
                    { min: 1, max: 50, message: '作者名长度为1-50位', trigger: 'blur' }
                ],
                publisher: [
                    { required: true, message: '请输入出版社', trigger: 'blur' }
                ],
                publicationYear: [
                    { required: true, message: '请输入出版年份', trigger: 'blur' }
                ],
                category: [
                    { required: true, message: '请选择图书分类', trigger: 'change' }
                ],
                quantity: [
                    { required: true, message: '请输入总库存', trigger: 'blur' },
                    { type: 'number', min: 0, message: '总库存不能为负数', trigger: 'blur' }
                ],
                availableQuantity: [
                    { required: true, message: '请输入可借数量', trigger: 'blur' },
                    { type: 'number', min: 0, message: '可借数量不能为负数', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (value > this.bookForm.quantity) {
                                callback(new Error('可借数量不能大于总库存'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            }
        };
    },

    mounted() {
        // 页面加载时获取图书列表
        this.getBookList();
    },

    methods: {
        // 获取图书列表
        async getBookList() {
            this.tableLoading = true;
            try {
                // 构建请求参数（包含分页和搜索条件）
                const params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    ...this.searchForm
                };

                const response = await this.$axios.get('/books', { params });
                this.bookList = response.data.records;
                this.total = response.data.total;
            } catch (error) {
                this.$message.error('获取图书列表失败：' + (error.message || '网络错误'));
                console.error('获取图书列表失败：', error);
            } finally {
                this.tableLoading = false;
            }
        },

        // 搜索图书
        searchBooks() {
            this.pageNum = 1; // 搜索时重置到第一页
            this.getBookList();
        },

        // 重置搜索条件
        resetSearch() {
            this.searchForm = {
                title: '',
                author: '',
                isbn: ''
            };
            this.pageNum = 1;
            this.getBookList();
        },

        // 显示新增图书弹窗
        showAddModal() {
            this.dialogType = 'add';
            // 重置表单
            this.bookForm = {
                id: null,
                isbn: '',
                title: '',
                author: '',
                publisher: '',
                publicationYear: null,
                category: '',
                quantity: 0,
                availableQuantity: 0
            };
            // 重置表单验证状态
            if (this.$refs.bookForm) {
                this.$refs.bookForm.resetFields();
            }
            this.dialogVisible = true;
        },

        // 显示编辑图书弹窗
        showEditModal(row) {
            this.dialogType = 'edit';
            // 复制行数据到表单（深拷贝）
            this.bookForm = JSON.parse(JSON.stringify(row));
            this.dialogVisible = true;
        },

        // 保存图书（新增或编辑）
        async saveBook() {
            // 表单验证
            try {
                await this.$refs.bookForm.validate();
            } catch (error) {
                return; // 验证失败则不提交
            }

            try {
                if (this.dialogType === 'add') {
                    // 新增图书
                    await this.$axios.post('/books', this.bookForm);
                    this.$message.success('图书新增成功！');
                } else {
                    // 编辑图书
                    await this.$axios.put(`/books/${this.bookForm.id}`, this.bookForm);
                    this.$message.success('图书更新成功！');
                }
                // 关闭弹窗并刷新列表
                this.dialogVisible = false;
                this.getBookList();
            } catch (error) {
                this.$message.error(
                    (this.dialogType === 'add' ? '新增' : '更新') +
                    '图书失败：' + (error.response?.data?.message || error.message)
                );
                console.error('保存图书失败：', error);
            }
        },

        // 删除单本图书
        async deleteBook(id) {
            try {
                await this.$confirm('确定要删除这本图书吗？', '确认删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                await this.$axios.delete(`/books/${id}`);
                this.$message.success('图书删除成功！');
                this.getBookList();
            } catch (error) {
                // 如果是取消操作，不显示错误信息
                if (error !== 'cancel') {
                    this.$message.error('删除图书失败：' + (error.message || '操作失败'));
                }
            }
        },

        // 处理表格选择变化
        handleSelectionChange(selection) {
            this.selectedBooks = selection;
        },

        // 确认批量删除
        async confirmBatchDelete() {
            if (this.selectedBooks.length === 0) {
                this.$message.warning('请先选择要删除的图书');
                return;
            }

            try {
                // 获取选中图书的ID列表
                const ids = this.selectedBooks.map(book => book.id);
                await this.$axios.post('/books/batch-delete', { ids });

                this.$message.success(`成功删除 ${this.selectedBooks.length} 本图书！`);
                this.batchDeleteDialog = false;
                this.getBookList();
            } catch (error) {
                this.$message.error('批量删除失败：' + (error.message || '操作失败'));
                console.error('批量删除失败：', error);
            }
        },

        // 处理每页条数变化
        handleSizeChange(val) {
            this.pageSize = val;
            this.getBookList();
        },

        // 处理页码变化
        handleCurrentChange(val) {
            this.pageNum = val;
            this.getBookList();
        }
    }
};
</script>

<style scoped>
.book-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.search-card {
    padding: 15px;
}

.table-card {
    padding: 15px;
}

.pagination {
    margin-top: 15px;
    text-align: right;
}

.book-form {
    margin-top: 10px;
}

.text-success {
    color: #10b981;
    font-weight: 500;
}

.text-danger {
    color: #ef4444;
    font-weight: 500;
}
</style>
